# coding:utf-8
__author__ = "ila"

from flask import session, jsonify, request
from . import main_bp
from utils.codes import *
from api.models.shangjia import shangjia
from utils.jwt_auth import Auth
from utils import message as mes
from api.models.bijiben import bijiben
from api.models.diannaozhuji import diannaozhuji
from api.models.yingjianzuzhuang import yingjianzuzhuang
from api.models.diannaowaishe import diannaowaishe

@main_bp.route("/python758879l3/shangjia/register", methods=['POST'])
def python758879l3_shangjia_register():
    if request.method == 'POST':
        msg = {'code': normal_code, 'msg': 'success'}
        req_dict = session.get("req_dict")

        error = shangjia.createbyreq(shangjia, shangjia, req_dict)
        if error != None:
            msg['code'] = crud_error_code
            msg['msg'] = "注册用户已存在"
        return jsonify(msg)
@main_bp.route("/python758879l3/shangjia/login", methods=['GET', 'POST'])
def python758879l3_shangjia_login():
    if request.method == 'GET' or request.method == 'POST':
        msg = {'code': normal_code, 'msg': 'success'}
        req_dict = session.get("req_dict")

        datas = shangjia.getbyparams(shangjia, shangjia, req_dict)
        if not datas:
            msg['code'] = password_error_code
            msg['msg'] = '登录失败'
            return jsonify(msg)

        if datas[0].get('status') != 1:
            msg['code'] = password_error_code
            msg['msg'] = '账号已被禁用'
            return jsonify(msg)

        req_dict['id'] = datas[0].get('id')
        return Auth.authenticate(Auth, shangjia, req_dict)
@main_bp.route("/python758879l3/shangjia/session", methods=['GET'])
def python758879l3_shangjia_session():
    if request.method == 'GET':
        msg = {"code": normal_code, "data": {}}
        req_dict = {"id": session.get('params').get("id")}
        msg['data'] = shangjia.getbyparams(shangjia, shangjia, req_dict)[0]
        return jsonify(msg)
@main_bp.route("/python758879l3/shangjia/page", methods=['GET'])
def python758879l3_shangjia_page():
    if request.method == 'GET':
        msg = {"code": normal_code, "msg": "success", "data": {}, "pagination": {}}
        
        # 初始化请求参数
        req_dict = {
            'page': request.args.get('page', 1),
            'limit': request.args.get('limit', 10)
        }
        
        try:
            # 检查表结构
            print("商家表名：", shangjia.__tablename__)
            print("商家表字段：", [column.name for column in shangjia.__table__.columns])
            
            # 直接查询并打印详细信息
            test_query = shangjia.query.all()
            print("查询到的记录数：", len(test_query))
            
            # 打印每条记录的详细信息
            for item in test_query:
                print("商家记录：", {
                    'id': getattr(item, 'id', None),
                    'shangjiazhanghao': getattr(item, 'shangjiazhanghao', None),
                    'shangjiamingcheng': getattr(item, 'shangjiamingcheng', None)
                })
            
            # 执行分页查询
            result = shangjia.page(shangjia, shangjia, req_dict)
            msg['data']['list'], msg['pagination']['page'], msg['pagination']['pages'], \
            msg['pagination']['total'], msg['pagination']['limit'] = result
            
        except Exception as e:
            print("查询错误：", str(e))
            msg['code'] = crud_error_code
            msg['msg'] = str(e)
            
        return jsonify(msg)
@main_bp.route("/python758879l3/shangjia/<type>/page", methods=['GET'])
def shangjia_product_page(type):
    if request.method == 'GET':
        msg = {'code': normal_code, 'msg': 'success', 'data': {}}
        try:
            page = int(request.args.get('page', 1))
            limit = int(request.args.get('limit', 10))
            shangjiaid = request.args.get('shangjiaid')
            print('商家ID====>'+shangjiaid)
            model_map = {
                'bijiben': bijiben,
                'diannaozhuji': diannaozhuji,
                'yingjianzuzhuang': yingjianzuzhuang,
                'diannaowaishe': diannaowaishe
            }
            
            model = model_map.get(type)
            if not model:
                msg['code'] = crud_error_code
                msg['msg'] = '无效的商品类型'
                return jsonify(msg)

            # 修改查询条件字段名为 shangjia_id
            query = model.query.filter_by(shangjia_id=shangjiaid)
            
            total = query.count()
            start = (page - 1) * limit
            data = query.offset(start).limit(limit).all()
            
            result_list = []
            for item in data:
                item_dict = {}
                for column in item.__table__.columns:
                    item_dict[column.name] = getattr(item, column.name)
                result_list.append(item_dict)
            
            msg['data'] = {
                'total': total,
                'list': result_list
            }
            
        except Exception as e:
            msg['code'] = crud_error_code
            msg['msg'] = str(e)
            
        return jsonify(msg)

@main_bp.route("/python758879l3/shangjia/<type>/delete/<id>", methods=['DELETE'])
def shangjia_product_delete(type, id):
    if request.method == 'DELETE':
        msg = {'code': normal_code, 'msg': 'success'}
        try:
            shangjiaid = request.args.get('shangjiaid')
            
            model_map = {
                'bijiben': bijiben,
                'diannaozhuji': diannaozhuji,
                'yingjianzuzhuang': yingjianzuzhuang,
                'diannaowaishe': diannaowaishe
            }
            
            model = model_map.get(type)
            if not model:
                msg['code'] = crud_error_code
                msg['msg'] = '无效的商品类型'
                return jsonify(msg)

            # 修改查询条件字段名为 shangjia_id
            item = model.query.filter_by(id=id, shangjia_id=shangjiaid).first()
            if not item:
                msg['code'] = crud_error_code
                msg['msg'] = '商品不存在或无权限删除'
                return jsonify(msg)

            db.session.delete(item)
            db.session.commit()
            
        except Exception as e:
            msg['code'] = crud_error_code
            msg['msg'] = str(e)
            
        return jsonify(msg)
def python758879l3_shangjia_info(id_):
    if request.method == 'GET':
        msg = {"code": normal_code, "msg": "success", "data": {}}
        data = shangjia.getbyid(shangjia, shangjia, int(id_))
        if len(data) > 0:
            msg['data'] = data[0]
        return jsonify(msg)

@main_bp.route("/python758879l3/shangjia/update", methods=['POST'])
def python758879l3_shangjia_update():
    if request.method == 'POST':
        msg = {"code": normal_code, "msg": "success"}
        req_dict = session.get('req_dict')

        error = shangjia.updatebyparams(shangjia, shangjia, req_dict)
        if error != None:
            msg['code'] = crud_error_code
            msg['msg'] = mes.crud_error_code
        return jsonify(msg)

@main_bp.route("/python758879l3/shangjia/delete", methods=['POST'])
def python758879l3_shangjia_delete():
    if request.method == 'POST':
        msg = {"code": normal_code, "msg": "success"}
        req_dict = session.get('req_dict')

        error = shangjia.delete(shangjia, req_dict)
        if error != None:
            msg['code'] = crud_error_code
            msg['msg'] = mes.crud_error_code
        return jsonify(msg)

@main_bp.route("/python758879l3/shangjia/review", methods=['POST'])
def python758879l3_shangjia_review():
    if request.method == 'POST':
        msg = {"code": normal_code, "msg": "success"}
        req_dict = session.get('req_dict')

        if not Auth.identify(session.get("token"), 2):
            msg['code'] = 401
            msg['msg'] = "无权限"
            return jsonify(msg)

        error = shangjia.updatebyparams(shangjia, shangjia, req_dict)
        if error != None:
            msg['code'] = crud_error_code
            msg['msg'] = mes.crud_error_code
        return jsonify(msg)